package com.njupt.Tree;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @Author: wujiaming
 * @CreateTime: 2024/11/22 21:37
 * @Description:  104 二叉树的最大深度
 * @Version: 1.0
 */


public class MaxDepth {

    /**
     *
     * 递归法
     * @param root
     * @return
     */
    public int maxDepth(TreeNode root) {
        int leftDepth,rightDepth;
        if(root == null) return 0;

        leftDepth =  maxDepth(root.left) ;
        rightDepth =  maxDepth(root.right) ;

        return leftDepth>rightDepth? leftDepth+1:rightDepth+1;
    }

    /**
     * 层次遍历法求二叉树的深度
     * @param root
     * @return
     */
    public int maxDepth1(TreeNode root){
        Deque<TreeNode> queue = new LinkedList<>();
        if(root == null) return 0;
        queue.addLast(root);
        int depth = 0;
        while(!queue.isEmpty()){
            int size = queue.size();
            depth++;
            for (int i = 0; i < size; i++) {
                TreeNode treeNode = queue.pollFirst();
                if(treeNode.left != null){
                    queue.addLast(treeNode.left);

                }
                if(treeNode.right != null){
                    queue.addLast(treeNode.right);
                }

            }
        }
        return depth;

    }

    /**
     * 二叉树的中序遍历非递归算法，求二叉树的深度
     * @param root
     * @return
     */
    public int maxDepth2(TreeNode root){
        Deque<TreeNode> stack1 = new LinkedList<>();
        Deque<Integer> stack2 = new LinkedList<>();
        int maxDepth = 0;
        int currentDepth = 0;
        if(root == null) return  maxDepth;
        TreeNode cur = root;
        while(cur != null || !stack1.isEmpty()){
            if(cur != null){
                stack1.push(cur);
                stack2.push(++currentDepth);
                cur = cur.left;
            }else {
                cur = stack1.pop();
                currentDepth = stack2.pop();
                if(currentDepth>maxDepth){
                    maxDepth = currentDepth;
                }
                cur = cur.right;
            }
        }
        return maxDepth;

    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);

        MaxDepth test = new MaxDepth();
        int depth = test.maxDepth2(root);
        System.out.println(depth);
    }
}
